package com.huayi.datagovernance.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.huayi.datagovernance.common.SysConstant;
import com.huayi.datagovernance.dao.master.TYDao;
import com.huayi.datagovernance.dto.DataBrokerDto;
import com.huayi.datagovernance.dto.Point;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 数据代理新增util
 */
@Component
public class DataBrokerUtil {
    Logger log = LoggerFactory.getLogger(this.getClass());

    @Value("${dataService.rest.data.oid}")
    private String getOidUrl;

    @Value("${dataService.rest.data.save}")
    private String saveUrl;

    @Value("${dataService.rest.data.update}")
    private String updateUrl;

    @Value("${dataService.rest.data.delete}")
    private String deleteUrl;

    @Value("${dataService.rest.data.query}")
    private String getInfoUrl;

    @Resource
    private TYDao tyDao;

    @Autowired
    private ShapeUtil shapeUtil;
    /**
     * 获取oid
     * @param tableName
     * @return
     */
    public String getOid(String tableName){
        String result= HttpUtil.sendGet(getOidUrl+"/"+tableName,null);
        JSONObject jsonResult= JSONObject.parseObject(result);
        if(jsonResult.get("code")!=null&&StringUtils.equals(jsonResult.getString("code"),"10000")){
            return jsonResult.getString("resultValue");
        }else {
            log.info(jsonResult.getString("message"));
            return jsonResult.getString("message");
        }
    }


    /**
     * 保存
     * @param param
     * @return
     */
    public String save(String param){
        String result= HttpUtil.sendPost(saveUrl,param);
        JSONObject jsonResult= JSONObject.parseObject(result);
        if(jsonResult.get("code")!=null&&StringUtils.equals(jsonResult.getString("code"),"10000")){
            return "created";
        }else {
            String str=jsonResult.get("message")==null?"代理服务访问失败！":jsonResult.getString("message");
            log.info(str);
            return str;
        }
    }


    /**
     * 修改
     * @param param
     * @return
     */
    public String update(String param){
        String result= HttpUtil.sendPost(updateUrl,param);
        JSONObject jsonResult= JSONObject.parseObject(result);
        if(jsonResult==null){return "";}
        if(jsonResult.get("code")!=null&&StringUtils.equals(jsonResult.getString("code"),"10000")){
            return "updated";
        }else {
            String str=jsonResult.get("message")==null?"代理服务访问失败！":jsonResult.getString("message");
            log.info(str);
            return str;
        }
    }


    /**
     * 删除
     * @param param
     * @return
     */
    public String delete(String param){
        String result=HttpUtil.sendPost(deleteUrl,param);
        JSONObject jsonResult= JSONObject.parseObject(result);
        if(jsonResult==null){return "";}
        if(jsonResult.get("code")!=null&&StringUtils.equals(jsonResult.getString("code"),"10000")){
            return "deleted";
        }else {
            String str=jsonResult.get("message")==null?"代理服务访问失败！":jsonResult.getString("message");
            log.info(str);
            return str;
        }
    }

    /**
     * 获取单个设备info
     * @param oid 主键
     * @param sbzlx 设备子类型
     * @return
     */
    public JSONObject getInfo(String oid, String sbzlx){
        JSONObject param =new JSONObject();
        param.put("oid",oid);
        param.put("sbzlx",sbzlx);
        log.info("数据代理查设备：["+getInfoUrl+",param="+param.toJSONString()+"]");
        String result=HttpUtil.sendPost(getInfoUrl,param.toJSONString());
        log.info("数据代理查设备结果：["+result+"]");
        JSONObject jsonResult= JSONObject.parseObject(result);
        if(jsonResult==null){return null;}
        if(jsonResult.get("code")!=null&&StringUtils.equals(jsonResult.getString("code"),"10000")){
            JSONObject jsonObject=jsonResult.getJSONObject("resultValue");
            if(jsonObject==null||StringUtils.isEmpty(jsonObject.toJSONString())){
                return null;
            }
            JSONObject jsonObjectNew =new JSONObject();
            //转小写
            for(String key :jsonObject.keySet()){
                jsonObjectNew.put(key.toLowerCase(),jsonObject.get(key));
            }
            return jsonObjectNew;
        }else {
            log.info("代理获取设备信息失败："+jsonResult.getString("message"));
            return null;
        }
    }


    /**
     * 格式化代理服务的数据
     * @param jsonArray
     * @return
     */
    public String formatData1(JSONArray jsonArray){
        DataBrokerDto dataBrokerDto =new DataBrokerDto();
        List<DataBrokerDto.PowerSystemResource> powerSystemResources =new ArrayList<>();
        for(int i=0;i<jsonArray.size();i++) {
            DataBrokerDto.PowerSystemResource powerSystemResource = new DataBrokerDto.PowerSystemResource();
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            /**
             * psrAttributes参数
             */
            List<DataBrokerDto.PSRAttribute> psrAttributes = new ArrayList<>();
            for (String key : jsonObject.keySet()) {
                if (StringUtils.equals(key.toLowerCase(), "oid")) {
                    powerSystemResource.setOid(jsonObject.getString(key));
                } else if (StringUtils.equals(key.toLowerCase(), "sbid")) {
                    powerSystemResource.setSbid(jsonObject.getString(key));
                } else if (StringUtils.equals(key.toLowerCase(), "sbzlx")) {
                    powerSystemResource.setModelid(jsonObject.getString(key));
                }
                else {
                    if(StringUtils.equals(key.toLowerCase(), "connection")){
                        log.info("-----------------");
                    }
                    else {
                        psrAttributes.add(new DataBrokerDto.PSRAttribute(key, jsonObject.getString(key)));
                    }
                }
            }
            powerSystemResource.setPSRAttributes(psrAttributes);

            /**
             * 坐标
             */
            DataBrokerDto.Geometry geometry =new DataBrokerDto.Geometry();
            List<Point> points =new ArrayList<>();
            if(jsonObject.get("points")!=null&&jsonObject.get("geotype")!=null){//坐标
                JSONArray pointJson=jsonObject.getJSONArray("points");
                for(int j=0;j<pointJson.size();j++){
                    Point point = JSONObject.parseObject(pointJson.getString(j),Point.class);
                    points.add(new Point(point.getX()+0.002,point.getY()+0.003));
                }
            }
            else {
                if(jsonObject.get("x")!= null&&jsonObject.get("y")!= null){
                    points.add(new Point(jsonObject.getDouble("x")+0.002,jsonObject.getDouble("y")+0.003));
                }
                if(jsonObject.get("qdsbX")!= null&&jsonObject.get("qdsbY")!= null
                        &&jsonObject.get("zdsbX")!= null&&jsonObject.get("zdsbY")!= null){
                    if(jsonObject.get("zxdsbX")!= null&&jsonObject.get("zxdsbY")!=null){//中心点设备(变压器)
                        points.add(new Point(jsonObject.getDouble("zxdsbX")+0.002,jsonObject.getDouble("zxdsbY")+0.003));
                    }
                    points.add(new Point(jsonObject.getDouble("qdsbX")+0.002,jsonObject.getDouble("qdsbY")+0.003));
                    points.add(new Point(jsonObject.getDouble("zdsbX")+0.002,jsonObject.getDouble("zdsbY")+0.003));
                }
            }
            geometry.setCoordinates(points);
            geometry.setType(SysConstant.SHAPE_TYPE.get(jsonObject.get("geotype")));
            powerSystemResource.setGeometry(geometry);

            powerSystemResources.add(powerSystemResource);
        }
        dataBrokerDto.setPowerSystemResources(powerSystemResources);
        String returnParam= JSONObject.toJSONString(dataBrokerDto, SerializerFeature.WriteMapNullValue);
        log.info("代理服务传参："+returnParam);
        return returnParam;
    }

    /**
     * 格式化代理服务的数据
     * @param jsonArray
     * @param operate 操作类型 SysConstant.operate_add...
     * @return
     */
    public String formatData(JSONArray jsonArray, int operate){
        List<Map> options =tyDao.getOptionsByField(ParamSet.DB_FIELD_CKZT);
        List<Double> offset =shapeUtil.getOffSet();//偏移量
        DataBrokerDto dataBrokerDto =new DataBrokerDto();
        List<DataBrokerDto.PowerSystemResource> powerSystemResources =new ArrayList<>();
        for(int i=0;i<jsonArray.size();i++) {
            DataBrokerDto.PowerSystemResource powerSystemResource = new DataBrokerDto.PowerSystemResource();
            JSONObject jsonObject = jsonArray.getJSONObject(i);

            /**
             * psrAttributes参数
             */
            List<DataBrokerDto.PSRAttribute> psrAttributes = new ArrayList<>();
            for (String key : jsonObject.keySet()) {
                if(Arrays.asList(ParamSet.dataBrokerNoField).contains(key.toLowerCase())){//排除可能出错的数据代理字段
                    continue;
                }else if (StringUtils.equals(key.toLowerCase(), "oid")) {//oid
                    powerSystemResource.setOid(jsonObject.getString(key));
                } else if (StringUtils.equals(key.toLowerCase(), "sbid")) {//sbid
                    powerSystemResource.setSbid(jsonObject.getString(key));
                } else if (StringUtils.equals(key.toLowerCase(), "sbzlx")) {//设备子类型
                    powerSystemResource.setModelid(jsonObject.getString(key));
                    //设备中有ckzt字段默认传输
                    if(jsonObject.get(ParamSet.DB_FIELD_CKZT)==null&&StringUtils.isNotEmpty(jsonObject.getString(ParamSet.DB_FIELD_CKZT))){
                        for(Map map:options){
                            if(StringUtils.equals(jsonObject.getString(key),map.get("modelid").toString())){
                                psrAttributes.add(new DataBrokerDto.PSRAttribute(ParamSet.DB_FIELD_CKZT, ParamSet.DB_FIELD_CKZT_VALUE));
                                break;
                            }
                        }
                    }
                }else if(StringUtils.equals(key.toLowerCase(), "connection")){//端子号
                    log.info("-----------------");
                }else if(StringUtils.equals(key.toLowerCase(), "dydj")){//电压等级
                    //DYDJ为空判断
                    if(jsonObject.get(key)==null||StringUtils.isEmpty(jsonObject.getString(key))||jsonObject.getInteger(key)==0){
                        Map modelType=tyDao.getModelNameByType(null,jsonObject.getString("sbzlx"));
                        //中压
                        if(modelType.get("modelname").toString().contains("zwyc")||modelType.get("modelname").toString().contains("znyc")){
                            psrAttributes.add(new DataBrokerDto.PSRAttribute(key, "22"));
                        }
                        //低压
                        else if(modelType.get("modelname").toString().contains("dysb")){
                            psrAttributes.add(new DataBrokerDto.PSRAttribute(key, "08"));
                        }
                    }else {
                        psrAttributes.add(new DataBrokerDto.PSRAttribute(key, jsonObject.getString(key)));
                    }
                }else  {
                    //不为空
                    if(StringUtils.isNotEmpty(jsonObject.getString(key))){
                        psrAttributes.add(new DataBrokerDto.PSRAttribute(key, jsonObject.getString(key)));
                    }
                }
            }
            powerSystemResource.setPSRAttributes(psrAttributes);

            /**
             * 坐标
             */
            DataBrokerDto.Geometry geometry =new DataBrokerDto.Geometry();
            List<Point> points =new ArrayList<>();
            if(jsonObject.get("points")!=null&&jsonObject.get("geotype")!=null){//坐标
                JSONArray pointJson=jsonObject.getJSONArray("points");
                for(int j=0;j<pointJson.size();j++){
                    Point point = JSONObject.parseObject(pointJson.getString(j),Point.class);
                    points.add(point);
                }
            }
            else {
                if(jsonObject.get("x")!= null&&jsonObject.get("y")!= null){
                    points.add(new Point(jsonObject.getDouble("x"),jsonObject.getDouble("y")));
                }
                if(jsonObject.get("qdsbX")!= null&&jsonObject.get("qdsbY")!= null
                        &&jsonObject.get("zdsbX")!= null&&jsonObject.get("zdsbY")!= null){
                    if(jsonObject.get("zxdsbX")!= null&&jsonObject.get("zxdsbY")!=null){//中心点设备(变压器)
                        points.add(new Point(jsonObject.getDouble("zxdsbX"),jsonObject.getDouble("zxdsbY")));
                    }
                    points.add(new Point(jsonObject.getDouble("qdsbX"),jsonObject.getDouble("qdsbY")));
                    points.add(new Point(jsonObject.getDouble("zdsbX"),jsonObject.getDouble("zdsbY")));
                }
            }
            //编辑的时候加偏移量（入库加，出库减去）
            if(SysConstant.operate_edit==operate){
                List<Point> points1 =new ArrayList<>();
                for(Point pp:points){
                    pp.setX(pp.getX()+offset.get(0));
                    pp.setY(pp.getY()+offset.get(1));
                    points1.add(pp);
                }
                points=points1;
            }
            geometry.setCoordinates(points);
            geometry.setType(SysConstant.SHAPE_TYPE.get(jsonObject.get("geotype")));
            powerSystemResource.setGeometry(geometry);

            powerSystemResources.add(powerSystemResource);
        }
        dataBrokerDto.setPowerSystemResources(powerSystemResources);
        String returnParam= JSONObject.toJSONString(dataBrokerDto, SerializerFeature.WriteMapNullValue);
        log.info("代理服务传参："+returnParam);
        return returnParam;
    }

}
